package com.example.demo.controller;

import com.example.demo.entity.UserBean;
import com.example.demo.service.UserService;
import com.example.demo.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @PostMapping("/admin/login")
    public ResponseEntity doLogin(@RequestBody UserBean userBean){
        ResponseEntity data = userService.login(userBean);
        return  data;
    }

    // 1.接受用户上传的文件？？
    @PostMapping("/upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file){
        // file 拥有 图片全部信息
        // 名称,类型，大小
        String filename = file.getOriginalFilename();
        System.out.println(file.getOriginalFilename());
        //TODO 限制必须是图片
        //TODO 大小不超过10MB
        //TODO 名称不重复（uuid，date+random）
        // 2. 转存到服务器
        // 路径+文件名字
        String  path = "D:/images/"+filename;
        try {
            file.transferTo(new File(path));

            // 3. 返回图片地址url
            String url = "/images/"+filename;

            HashMap<String, String> map = new HashMap<>();
            map.put("url",url);
            return  new ResponseEntity(200,"上传成功",map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.failed("上传失败");
    }
}
